/*********************************************************************************
 *      Copyright:  (C) 2022 Zhang Changxing<ZhangChangxingVIP@163.com>
 *                  All rights reserved.
 *
 *       Filename:  main.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(04/13/2022)
 *         Author:  Zhang Changxing <ZhangChangxingVIP@163.com>
 *      ChangeLog:  1, Release initial version on "04/13/2022 01:42:54 AM"
 *                 
 ********************************************************************************/

#include "main.h"


#define TABLE_NAME  "RPI5"
#define DB_NAME "temperature"
int		g_sigstop = 0;

static inline  void print_usage(char *programe);


int main (int argc, char **argv)
{
	float 				temp = 0;
	int 				rv = -1;
	int					ch;
	int					daemon_run =0;
	int 				con_status = 1;
	char 				datime[100];
	static double 		current_time = 0;
	static double 		latest_time = 0;
	int 				sockfd = -1;
	int					port =0;
	char				*ip_addr = NULL;
	static int 			count = 0;
	int 				con_rv = -1;
	pack_info_t			pack_info;
	int					interval = 4; /*The default sampling interval is 4 seconds*/

    if( logger_init("../logger/running.log", LOG_LEVEL_INFO) < 0)
    {
        fprintf(stderr, "initial logger system failure\n");
        return -1;
    }

	log_error("\n\n\n");
	log_error("*************************************************************************");
	log_error("*                     The client starts running                         *");
	log_error("*************************************************************************\n");

	struct option opts[] = {
		{"time_interval",required_argument, NULL, 't'},
		{"ip_addr", required_argument, NULL, 'i'},
		{"port", required_argument, NULL, 'p'},
		{"daemon", no_argument, NULL, 'b'},
		{"help", no_argument, NULL, 'h'},
		{0, 0, 0, 0}
	}; 

	while ((ch = getopt_long(argc, argv, "t:i:p:bh", opts, NULL)) != -1)
	{
		switch (ch)
		{
			case 't':
			{
				interval = atoi(optarg);
				break;
			}
			case 'i':
				{
					ip_addr = optarg;
					break;
				}
			case 'p':
				{
					port = atoi(optarg);
					break;
				}
			case 'b':
				{
					daemon_run = 1;
					break;
				}
			case 'h':
				{
					print_usage(argv[0]);
					return 0;
				}
			default:
				{
					log_error("Invalid argument\n");
					return -1;
				}
		}
	}
	
	if (port == 0 || ip_addr == NULL)
	{
		log_error("Invalid port or IP address is NULL!\n");
		return -2;
	}

	if (daemon_run)
	{
		if (daemon(1, 1))
		{
			log_error("Running daemon failure:%s\n", strerror(errno));
		}
		log_debug("Running daemon successfully!\n");
	}

	signal(SIGINT, SIG_IGN);

	con_rv = connect_socket(&sockfd, port, ip_addr);
	if (con_rv < 0)
	{
		con_status =0;
	}

	if (sqlite_init(DB_NAME))
	{
		return -3;
	}

	/*sqlite_create_table() is always executed if the table fails to be created*/
	if(sqlite_create_table(TABLE_NAME))
	{
		close_database();
		return -4;
	}
	
	current_time = 0;

	while (!g_sigstop)
	{
		latest_time = getime(NULL);
		if ((latest_time - current_time) >= interval)
		{
			if((rv = temperature(&temp))< 0)
			{
				printf("Execute temperature failure!\n");
				return -5;
			}
			current_time = getime(datime);

			memset(&pack_info, 0, sizeof(pack_info));
			strcpy(pack_info.devid, TABLE_NAME);
			strcpy(pack_info.strtime, datime);
			pack_info.temper = temp;

			log_debug("pack_info.devid:%s  pack_info.strtime:%s pack_info.temper:%f\n",\
			pack_info.devid, pack_info.strtime, pack_info.temper);

			#if 1
			if (get_sock_status(sockfd) == -2)
			{
				con_status = 0;
			}

			if (con_status)
			{
				if (sendata(sockfd, pack_info) < 0)
				{
					con_status = 0;
					data_insert(pack_info, TABLE_NAME);
					close(sockfd);
				}
			}
			else
			{
				data_insert(pack_info, TABLE_NAME);
				close(sockfd);
			}
			#endif
		}
		else if (check_table_data(TABLE_NAME) >0)
		{
			#if 1
			if (get_sock_status(sockfd) == -2)
			{
				con_status = 0;
			}
			if (con_status)
			{
				select_first_data(&pack_info,  TABLE_NAME);
				if (sendata(sockfd,pack_info) < 0)
				{
					con_status = 0;
					close(sockfd);
				}
				else
				{
					if (data_delete(TABLE_NAME) == 0)
					{
						log_debug("Delete first data successfully!\n");
					}
				}
			}
			else
			{
				con_rv = connect_socket(&sockfd, port, ip_addr);
				if (con_rv < 0)
				{
					con_status = 0;
					close(sockfd);
				}
				else
				{
					con_status = 1;
				}
			}
			#endif
		}
	
	}

    return 0;
}

/*print help information */
static inline  void print_usage(char *programe)
{
	printf("Usage:%s[OPTION]....\n", programe);
	printf("\n-t[interval]:Gets the sampling interval, in seconds!\n");
	printf("-p[port]:Socket sever port address\n");
	printf("-b[daemon]:Start daemon!\n");
	printf("-h[help]:Display this help information\n");
	printf("\nExample:%s -b -p 6667 -i 127.0.0.1 -t 30\n\n", programe);
	return;
}




